//
//  TodayController.m
//  Water
//
//  Created by chenguibang on 2017/11/26.
//  Copyright © 2017年 chenguibang. All rights reserved.
//

#import "TodayController.h"
#import "WaterCell.h"
#import "TodayStatisticsController.h"
#import "PlanController.h"
#import <Masonry/Masonry.h>
#import <BlocksKit/BlocksKit+UIKit.h>
@interface TodayController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@end

@implementation TodayController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.todayView];
    [self.todayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
   
    

    [self.viewModel addObserver:self forKeyPath:@"weatherInfo" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    [self.viewModel addObserver:self forKeyPath:@"current" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    [self.viewModel addObserver:self forKeyPath:@"total" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    
    [self.todayView.drinkTargetView.setBtn bk_whenTapped:^{
       
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入饮水量" preferredStyle:UIAlertControllerStyleAlert];
    
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            UITextField *tf = [alert.textFields firstObject];
            self.viewModel.total = [tf.text intValue];
            [AppClient shared].todayTarget = tf.text;
            [[AppClient shared] savePlans];
        }]];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
    }];
    
//    [self.todayView.drinkTargetView.totalTextFiled.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
//
//    }];
    [self.viewModel getWeather];
    self.viewModel.total = [[AppClient shared].todayTarget intValue];
    [[AppDataBaseManager shareManager] getTodayDrinkcallBack:^(int amount) {
        self.viewModel.current = amount;
    }];
}

- (TodayView *)todayView{
    if(!_todayView){
        _todayView = [[TodayView alloc]init];
        _todayView.waterCollectionView.delegate = self;
        _todayView.waterCollectionView.dataSource = self;
        [_todayView.waterCollectionView registerNib:[UINib nibWithNibName:@"WaterCell" bundle:nil] forCellWithReuseIdentifier:@"WaterCell"];
        [_todayView.recordBtn addTarget:self action:@selector(toStatistics) forControlEvents:UIControlEventTouchUpInside];
         [_todayView.makePlanBtn addTarget:self action:@selector(makePlan) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _todayView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
     self.navigationController.navigationBarHidden = NO;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.viewModel.waters.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WaterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WaterCell" forIndexPath:indexPath];
    cell.viewModel = self.viewModel.waters[indexPath.row];
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WaterCellModel *model =  self.viewModel.waters[indexPath.row];
    self.viewModel.current = self.viewModel.current + model.amount;
    [self.viewModel drinkWith:model];
}



- (void)toStatistics{
    TodayStatisticsController *todayStatisticsController =[TodayStatisticsController new];
    todayStatisticsController.title = @"今日记录";
    todayStatisticsController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:todayStatisticsController animated:YES];
}

- (void)makePlan{
    PlanController *plan = [[PlanController alloc]init];
    plan.title = @"定制计划";
    plan.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:plan animated:YES];
}


- (TodayViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[TodayViewModel alloc]init];
    }
   return _viewModel;
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if([keyPath isEqualToString:@"weatherInfo"]){
        self.todayView.weatherInfoLabel.text = [NSString stringWithFormat:@"城市:%@ \n温度:%@ \n湿度:%@ \n风向:%@ \n风力:%@\n建议饮水量:3045ml",self.viewModel.weatherInfo.city,self.viewModel.weatherInfo.temperature,self.viewModel.weatherInfo.humidity,self.viewModel.weatherInfo.direction,self.viewModel.weatherInfo.wind];
    }
    
    [self.todayView.circleAnimationView setPercent:(float)self.viewModel.current/(float)self.viewModel.total animated:NO];
    self.todayView.drinkTargetView.totalTextFiled.text = [NSString stringWithFormat:@"%d",self.viewModel.total];
    self.todayView.circleAnimationView.subTitle = [NSString stringWithFormat:@"已喝%d,余%dml",self.viewModel.current,(self.viewModel.total -self.viewModel.current) < 0 ? 0 :   (self.viewModel.total -self.viewModel.current)];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
